<template>
	<view class="flex flex-1 items-end bg-black" >
		<!-- 主播 -->
		<view class="flex flex-1 justify-between" v-if="room.role==='anchor'">
			<view class="flex items-end">
				<text style="color: #fff;width: 24rpx;font-size: 24rpx;margin-right: 10rpx;">游客</text>
				<AnchorVue :params="params" :pause="pause" algin="row" @startLocalAudio="startLocalAudio">
				</AnchorVue>
			</view>
			<!--  -->
			<view class="flex items-end">
				<text style="color: #fff;width: 24rpx;font-size: 24rpx;margin-right: 10rpx;">咨询师</text>
				<UserVue :params="userOption" :anonymous="true" :pause="pause" algin="row" :role="room.role"
					v-if="userOption.userId">
				</UserVue>
			</view>
		</view>
		<!-- 游客 -->
		<view class="flex flex-1  justify-between" v-if="room.role==='user'">
			<view class="flex items-end">
				<text style="color: #fff;width: 24rpx;font-size: 24rpx;margin-right: 10rpx;">咨询师</text>
				<UserVue :params="userOption" :pause="pause" :anonymous="true" :role="room.role" algin="row-reverse"
					v-if="userOption.userId"></UserVue>
			</view>
			<!--  -->
			<view class="flex items-end">
				<text style="color: #fff;width: 24rpx;font-size: 24rpx;margin-right: 10rpx;">游客</text>
				<view class="flex-1" v-if="connectingUserId">
					<AnchorVue :params="params" :pause="pause" v-if="params.userId==user.id" algin="row-reverse"
						role='user' @startLocalAudio="startLocalAudio" @memberVoiAnchorEnd="memberVoiAnchorEnd">
					</AnchorVue>
					<UserVue :params="params" :anonymous="true" :pause="pause" :role="room.role" algin="row" v-else>
					</UserVue>
				</view>

			</view>
		</view>
	</view>
</template>

<script setup>
	import liveApi from '@/apis/apiList/liveApi';
	import TrtcCloud from '@/TrtcCloud/lib/index';
	import AnchorVue from './Anchor.vue';
	import UserVue from './User.vue';
	import nvImage from '@/uni_modules/uv-image/components/uv-image/uv-image.vue'
	import {
		TRTCAppScene,
		TRTCRoleType,
		TRTCAudioRoute,
		TRTCVideoStreamType
	} from '@/TrtcCloud/lib/TrtcDefines';
	import TrtcLocalView from '@/TrtcCloud/view/TrtcLocalView';
	import TrtcRemoteView from '@/TrtcCloud/view/TrtcRemoteView';
	import {
		nextTick,
		ref,
	} from 'vue';
	import userApi from '@/apis/apiList/userApi';
	import dayjs from 'dayjs';
	let trtcCloud = TrtcCloud.createInstance(); //创建实例
	const videoRef = ref(null)
	const popupRef = ref(null)

	const room = ref({}) //直播间信息
	const pause = ref(true) //暂停
	const emit = defineEmits(['createCustomMessage', 'sendMsg', 'backRoom'])
	const user = uni.getStorageSync('user') //当前用户信息
	const liveOption = ref({}) //连接直播间必要参数
	const queueList = ref([]) //排序列表
	const connectingId = ref('') //麦序Id
	const connectingUserId = ref('') //连线用户Id
	const time = ref(0) //计时器
	const timeFormat = e => {
		return e ? dayjs().startOf('day').add(e, 'second').format('HH:mm:ss') : '00:00:00'
	}
	const params = ref({
		userId: "",
		headimg: '',
		nickname: '',
		live: false,
		audio: false
	})
	const userOption = ref({
		userId: "",
		headimg: '',
		nickname: '',
		live: false,
		audio: false
	})
	//初始化直播间
	const startLive = (options, anchorInfo, userInfo) => {
		console.log(options, anchorInfo, userInfo);
		liveOption.value = options
		room.value.role = options.role
		nextTick(() => {
			if (room.value.role == 'anchor') {
				// 主播
				params.value = {
					userId: anchorInfo.member.id,
					headimg: anchorInfo.headimg,
					nickname: anchorInfo.name,
					live: true,
					audio: true
				}
				setUserOption(userInfo)
			} else {
				liveApi.memberAddPriVoiOrder({
					'member.id': user.id,
					"anchor.id": anchorInfo.id,
					'payt': 0
				}).then(res => {
					console.log('麦序信息', res.data.id, res);
					connectingId.value = res.data.id
					userConnection(anchorInfo)
					// 用户
					userOption.value = {
						userId: anchorInfo.member.id,
						headimg: anchorInfo.headimg,
						nickname: anchorInfo.name,
						live: true,
						audio: true
					}
					setUserOption(user)
					// queryAnchorInfoByMemberId()
					// userConnection(userInfo, anchorInfo)
				})

			}
			// console.log(room.value.role);
			// 进入房间
			enterRoom(true)
			// 监听
			onMonitor()
			// 排麦列表
			// getLiveRoomVoilist()
		})
	}
	// const queryAnchorInfoByMemberId = (id) => {
	// 	userApi.queryAnchorInfoByMemberId({
	// 		"member.id": id
	// 	}).then(res => {
	// 		console.log(res);
	// 		userConnection()
	// 	})
	// }
	// 退出直播间
	const closeLive = () => {
		clearTimeout(VoiTime.value)
		enterRoom(false)
		offMonitor()
		return true
	}
	// 设置连麦配置
	// const anonymous = ref(true)
	const setUserOption = (e) => {
		// anonymous.value = true
		// connectingId.value = e.id
		connectingUserId.value = e.id
		if (room.value.role == 'anchor') {
			userOption.value = {
				userId: e.id,
				headimg: e.headimg,
				nickname: e.nickname,
				live: true,
				audio: true
			}
		}
		if (room.value.role == 'user') {
			params.value = {
				userId: e.id,
				headimg: e.headimg,
				nickname: e.nickname,
				live: true,
				audio: true
			}
			// 开启计时
		}
		startLocalAudio(true)
		console.log(room.value.role, params.value, userOption.value);
		console.log(params.value.userId, userOption.value.userId);
		// 用户才计时
		if (VoiTime.value == null) memberVoiAnchorAdd()
	}
	// 退出直播间
	const delUserOption = () => {
		connectingId.value = ''
		time.value = 0
		connectingUserId.value = ''
		if (room.value.role == 'anchor') userOption.value = {
			userId: '',
			headimg: '',
			nickname: '',
			live: false,
			audio: false
		}
		if (room.value.role == 'user') params.value = {
			userId: '',
			headimg: '',
			nickname: '',
			live: false,
			audio: false
		}

		clearTimeout(VoiTime.value)
	}
	// 暂停
	const pauseNum = ref(3)
	const onPause = () => {
		if (room.value.role == 'user' && pause.value) {
			if (pauseNum.value == 0) {
				uni.showToast({
					icon: 'none',
					title: `3次暂停数已用完`
				})
				return
			} else {
				uni.showToast({
					icon: 'none',
					title: `当前剩余暂停数${pauseNum.value}`
				})
			}
			pauseNum.value -= 1
		}
		if (pauseNum.value > 0) {
			const val = {
				data: 'use',
				description: "pause",
				extension: pause.value ? '1' : "0"
			}
			if (val.description == 'pause') pause.value = !pause.value
			emit('createCustomMessage', val)
			onUse(val)
		}
	}

	// 上麦
	const userConnection = (anchorInfo) => {
		const query = {
			id: connectingId.value,
			"anchor.id": anchorInfo.id
		}
		liveApi.anchorStartVoiOrder(query).then(res => {
			uni.showToast({
				icon: 'none',
				title: '上麦成功'
			})
			// getLiveRoomVoilist()
			// 通知刷新排麦列表
			// createCustomMessage('getLiveRoomVoilist')
		})
	}
	const VoiTime = ref(null)
	// 查询连麦时间
	const memberVoiAnchorAdd = () => {
		// if (connectingId.value) {
		time.value = time.value + 1
		if (time.value % 30 === 0 && room.value.role == 'user') {
			// 30秒
			liveApi.memberVoiAnchorAdd({
				id: connectingId.value
			}).then(res => {
				if (res.data.sts == 0) {} else if (res.data.sts == 1) {
					uni.showToast({
						icon: 'none',
						title: "剩余时长不足3分钟"
					})
				} else {
					uni.showToast({
						icon: 'none',
						title: "连麦已结束"
					})
					emit('backRoom')
					clearTimeout(VoiTime.value)
					VoiTime.value = null
				}
			})
		}
		VoiTime.value = setTimeout(() => {
			memberVoiAnchorAdd()
		}, 1000)
		// }
	}
	// 删除排麦用户
	const delConnection = (val) => {
		console.log(val);
		if (val.sts == 0) {
			// 删除连麦
			anchorDelVoiOrder(val.id)
		}
		if (val.sts == 1) {
			// 结束连麦
			memberVoiAnchorEnd(val.id)
		}
	}
	// 主播关闭连麦
	const anchorDelVoiOrder = (id) => {
		const params = {
			id: id || connectingId.value,
			"anchor.id": room.value.anchor.id
		}
		liveApi.anchorDelVoiOrder(params).then(res => {
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
		})
	}
	// 主播结束连麦
	const memberVoiAnchorEnd = (id) => {
		liveApi.memberVoiAnchorEnd({
			id: id || connectingId.value
		}).then(res => {
			clearTimeout(VoiTime.value)
			time.value = 0
			getLiveRoomVoilist()
			createCustomMessage('getLiveRoomVoilist')
			startLocalAudio(false)
		})
	}
	const onEnterRoom = (e) => {
		console.log('进入房间。。。。。。。。。。', e);
	}
	// 进入房间
	const enterRoom = (type) => {
		trtcCloud.on('onEnterRoom', onEnterRoom); //进房
		if (type) {
			const params = {
				...liveOption.value,

				role: TRTCRoleType.TRTCRoleAnchor,
			}
			console.log(params);
			trtcCloud.enterRoom(params, TRTCAppScene.TRTCAppSceneAudioCall); //进房
			startLocalAudio(true)
		} else {
			trtcCloud.exitRoom() //退房

		}
	}

	// 打开/关闭摄像头
	const startLocalPreview = (type) => {
		// params.value.live = !type
		// if (params.value.live) {
		// 	trtcCloud.startLocalPreview(true, liveOption.value.userId); //摄像头
		// } else {
		// 	trtcCloud.stopLocalPreview() //摄像头
		// }
	}


	// 通知直播间更新排麦列表
	const createCustomMessage = (type, val) => {
		emit('createCustomMessage', {
			data: 'use',
			description: type,
			extension: val || ""
		})
	}
	// 接受操作
	const onUse = (val) => {
		console.log('监听操作', val);
		if (val.data == 'audio') {
			// 连麦权限
			if (val.description.indexOf(user.value.id) == -1) {
				// 
				console.log('静音');
				trtcCloud.muteAllRemoteAudio(false) //非静音掉所有用户的声音
			} else {
				console.log('不静音');
				trtcCloud.muteAllRemoteAudio(true) //非静音掉所有用户的声音
			}
		}
		// 开启扬声器
		// TRTCAudioRoute.TRTCAudioRouteEarpiece  听筒  TRTCAudioRoute.TRTCAudioRouteSpeaker扬声器
		if (val.description == 'speaker') trtcCloud.setAudioRoute(val.extension == '0' ? TRTCAudioRoute
			.TRTCAudioRouteSpeaker : TRTCAudioRoute.TRTCAudioRouteEarpiece)
		// 静音
		if (val.description == 'mute') trtcCloud.muteLocalAudio(val.extension == '1');
		// 刷新排麦列表
		if (val.description == 'getLiveRoomVoilist') getLiveRoomVoilist()
		// 暂停
		if (val.description == 'pause') {
			if (val.extension == '0') {
				// 恢复
				pause.value = true
				console.log('恢复');
				memberVoiAnchorAdd()
				trtcCloud.muteAllRemoteAudio(false) //非静音掉所有用户的声音
			} else {
				// 暂停
				console.log('暂停');
				pause.value = false
				trtcCloud.muteAllRemoteAudio(true) //非静音掉所有用户的声音
				clearTimeout(VoiTime.value)
				VoiTime.value = null
			}
		}
		// 下麦
		if (val.description == 'break') {
			clearTimeout(VoiTime.value)
			connectingUserId.value = ""
			getLiveRoomVoilist()
			startLocalAudio(false)
			nextTick(() => {
				params.value.userId = ''
			})
		}
	}
	// 进入房间
	const onRemoteUserEnterRoom = (userId) => {
		console.log('进入room', userId);
		// emit('createCustomMessage', {
		// 	data: 'roomHot',
		// 	description: userId,
		// 	extension: `add`
		// })
		// 添加主播视频
		// if (room.value.role === 'user' && userOption.value.userId == '') userOption.value.userId = userId
		// else userOption.value.userId = userId
	}
	// 退出房间
	const onRemoteUserLeaveRoom = (res) => {
		console.log('退出room', res);
		// emit('createCustomMessage', {
		// 	data: 'roomHot',
		// 	description: userId,
		// 	extension: `add`
		// })
		liveApi.memberLeaveliveRoom({
			"member.id": res.userId,
			"liveroom.id": room.value.id
		})
		if (res.userId === room.value.anchor.member.id) {
			trtcCloud.muteAllRemoteAudio(true)
			// uni.navigateBack({
			// 	delta: 1
			// })
		}
		// if (room.value.role == 'anchor') emit('createCustomMessage', {
		// 	data: 'roomHot',
		// 	description: res.userId,
		// 	extension: `del`
		// })
		// const {
		// 	userId,
		// 	reason
		// } = res
		// if (userId === userOption.value.userId) userOption.value.userId = ""
		// tips.value.push(`${userId}${reason!==0?reason!==1?'踢出房间':'超时退出':'退出房间'}`)
	}
	// 查询用户信息
	const queryMemberInfo = (id) => {
		return userApi.queryMemberInfo({
			id: id
		})
	}

	// 视频
	const onUserVideoAvailable = (res) => {
		// const {
		// 	userId,
		// 	available
		// } = res;
		// // console.log('live', res);
		// userOption.value.live = available
		// nextTick(() => {
		// 	if (userId && available) {
		// 		trtcCloud.startRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSmall,
		// 			userId);
		// 		// tips.value.push(`${userId}开启视频`)
		// 	} else {
		// 		trtcCloud.stopRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSmall);
		// 		// tips.value.push(`${userId}关闭视频`)
		// 	}
		// })
	}
	// 打开/关闭麦克风
	const startLocalAudio = (type) => {
		params.value.audio = type
		if (type) {
			trtcCloud.startLocalAudio(); //麦克风
		} else {
			trtcCloud.stopLocalAudio(); //麦克风
		}
	}
	// 音频
	const onUserAudioAvailable = async (res) => {
		console.log('audio', res);
		const {
			userId,
			available
		} = res;
		trtcCloud.muteRemoteAudio(userId, false)
		// if (userId != userOption.value.userId) {
		// 	if (room.value.role != 'user') params.value.audio = available
		// 	else userOption.value.audio = available
		// }
		// trtcCloud.muteRemoteAudio(userId, false);
		// if (userId && available) {
		// console.log(connectingUserId.value);
		// tips.value.push(`${userId}开启声音`)
		// if (room.value.role == 'user') {
		// 	const val = await queryMemberInfo(userId)
		// 	userOption.value.userId = userId
		// 	userOption.value.audio = true
		// 	userOption.value.headimg = val.data.member.headimg
		// 	userOption.value.nickname = val.data.member.nickname
		// }

		// } else {
		// trtcCloud.muteRemoteAudio(userId, true)
		// 当远端用户关闭视频流时，停止订阅
		// tips.value.push(`${userId}关闭声音`)
		// }
		// userOption.value.audio = available
	}
	// 监听
	const onMonitor = () => {
		// 监听房间人员进入
		trtcCloud.on("onRemoteUserEnterRoom", onRemoteUserEnterRoom);
		// 监听房间人员离开
		trtcCloud.on("onRemoteUserLeaveRoom", onRemoteUserLeaveRoom);
		// // 监听房间其他人的视频
		// trtcCloud.on('onUserVideoAvailable', onUserVideoAvailable);
		// 监听房间其他人的音频
		// trtcCloud.on('onUserAudioAvailable', onUserAudioAvailable);
	}
	// 退出监听
	const offMonitor = () => {
		if (trtcCloud) {
			// 监听房间人员进入
			trtcCloud.off("onRemoteUserEnterRoom", onRemoteUserEnterRoom);
			// 监听房间人员离开
			trtcCloud.off("onRemoteUserLeaveRoom", onRemoteUserLeaveRoom);
			// // 监听房间其他人的视频
			// trtcCloud.off('onUserVideoAvailable', onUserVideoAvailable);
			// 监听房间其他人的音频
			// trtcCloud.off('onUserAudioAvailable', onUserAudioAvailable);
		}
	}
	defineExpose({
		startLive,
		closeLive,
		onUse,
		popupRef
	})
</script>

<style>
</style>